/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import java.awt.Image;
import java.awt.Toolkit;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Antonio
 */
public class Run extends javax.swing.JFrame {

      int block;
      String width;
      String type;
      String dia;
      String mes;
      String annio;
      String description;
      int id;
    
      public Run() {
        initComponents();
        fecha();
        this.setResizable(false);
        //determinar si existe una corrida para este dia.
        //jTextDate.disable();
    }
    /**
     * Metodo para determinar cuando modificara un type
     * @param block 
     */
    public Run(int block,int id)
    {
        this.setResizable(false);
        this.block=block;
        this.id = id;
        System.out.println("RUN block "+ this.block);
        initComponents();
        jButtonCreateModify.setText("Continue Run");
        fecha();
          try {
              getRun(id);
          } catch (SQLException ex) {
              Logger.getLogger(Run.class.getName()).log(Level.SEVERE, null, ex);
          }
    }
    
   
    
public void fecha()
{
        Calendar c1 = Calendar.getInstance();
         dia = Integer.toString(c1.get(Calendar.DATE));
         mes = Integer.toString(c1.get(Calendar.MONTH)+1);
        annio = Integer.toString(c1.get(Calendar.YEAR));
        
        
        String date= mes+"/"+dia+"/"+annio;
      //  System.out.println(date);    
        jTextDate.setText(date);   
}
   
private int caseWidth(String width)
{
   if("  38".equals(width)){
       return 0;
   } 
   else if ("  48".equals(width)){
       return 1;
   }
    else if ("  52".equals(width)){
       return 2;
   }
   return 0;
}


private int caseType(String type)
{
   if("ISO C1 / 2.0".equals(type)){
       return 0;
   } 
   else if ("ISO C1 / 2.5".equals(type)){
       return 1;
   }
    else if ("ISO C1 / 3.0".equals(type)){
       return 2;
   }
    else if ("ISO C1 / 4.0".equals(type)){
       return 3;
   }
    else if ("ISO C1 / 6.0".equals(type)){
       return 4;
   }
    else if ("ISO -  HT".equals(type)){
       return 5;
   }
   else if ("ISO - L  2.0".equals(type)){
       return 6;
   }
 return 0;          
           
}

public void getRun(int id) throws SQLException
{
    ResultSet rs;
    String query = "select * from run where id = '"+id+"';";
    Conexion conexion = new Conexion();
    conexion.starConexion();
     rs = conexion.excecuteresult(query);
      try{
        while (rs.next())
        {
          type = rs.getString(3);
          width  = rs.getString(4);
          description = rs.getString(5);
            System.out.println("Type:"+ type);
            System.out.println("Width:"+ width);
            System.out.println("Description: "+ description);
        }
        } catch(Exception e)
        {
            System.out.println("Problema al imprimir la base de datos "+e.getMessage());
        }
        conexion.closeConexion();
        
        jComboType.setSelectedIndex(caseType(type));
        jComboWidth.setSelectedIndex(caseWidth(width));
        jComboWidth.setEnabled(false);
        jTextDescription.setText(description);
        jTextDescription.setEditable(false);
}

public int selectMax ()throws SQLException
    {
       ResultSet rs;
        id=0;
        String query = "select max(id) from run";
        Conexion conexion = new Conexion();
        conexion.starConexion();
        rs = conexion.excecuteresult(query);
        try{
        while (rs.next())
        {
          id = rs.getInt(1);
            System.out.println(" MAXIMO ES: "+ id);
        }
        } catch(Exception e)
        {
            System.out.println("Problema al imprimir la base de datos "+e.getMessage());
        }
        conexion.closeConexion();
        return(id);
    }
            
        @Override
    public Image getIconImage() {
        Image retValue = Toolkit.getDefaultToolkit().
                getImage(ClassLoader.getSystemResource("image/logo.png"));
       return retValue;
    }    


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jTextDate = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextDescription = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();
        jButtonCreateModify = new javax.swing.JButton();
        jComboType = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jComboWidth = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setIconImage(getIconImage());

        jLabel1.setText("Date:");

        jTextDate.setEditable(false);
        jTextDate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextDateActionPerformed(evt);
            }
        });

        jLabel2.setText("Type:");

        jLabel3.setText("Description:");

        jTextDescription.setColumns(4);
        jTextDescription.setLineWrap(true);
        jTextDescription.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextDescriptionKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(jTextDescription);

        jButton2.setText("Back");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButtonCreateModify.setText("Create");
        jButtonCreateModify.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCreateModifyActionPerformed(evt);
            }
        });

        jComboType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ISO C1 / 2.0", "ISO C1 / 2.5", "ISO C1 / 3.0", "ISO C1 / 4.0", "ISO C1 / 6.0", "ISO -  HT", "ISO - L  2.0" }));

        jLabel4.setText("Width:");

        jComboWidth.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jComboWidth.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "  38", "  48", "  52" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(264, 264, 264)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE)
                        .addComponent(jButtonCreateModify, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(221, 221, 221))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(34, 34, 34)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jComboWidth, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jComboType, javax.swing.GroupLayout.Alignment.LEADING, 0, 229, Short.MAX_VALUE))
                            .addComponent(jTextDate, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(135, 135, 135)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jComboType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(64, 64, 64)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 74, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonCreateModify, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(54, 54, 54))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jTextDateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextDateActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextDateActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        Home home = new Home();
        home.setVisible(true);
        this.setVisible(false);
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    
    
    private void jButtonCreateModifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCreateModifyActionPerformed
        
        Object e = jComboType.getSelectedItem(); 
        type = String.valueOf(e);
        String query;
        Conexion conexion = new Conexion();
        conexion.starConexion();
        
        if (block==0){
         Object obj  = jComboWidth.getSelectedItem(); 
         width= String.valueOf(obj);
         description=jTextDescription.getText();
       
         query = "insert into run (Date,type,width,description) values "
                + "('"+dia+"/"+mes+"/"+annio+"','"+type+"','"+width+"','"+description+"');";
 
         conexion.execute(query);        
         conexion.closeConexion();
         try {
              id = selectMax();
          } catch (SQLException ex) {
              Logger.getLogger(Run.class.getName()).log(Level.SEVERE, null, ex);
             }
        
            CreateProduct createProduct = new CreateProduct(type,id);
            createProduct.setVisible(true);
            this.setVisible(false);
        }
        else{ //modifico el tipo de corrida
         
         query ="update run set type = '"+type+"' where id="+id+";";
         conexion.execute(query);        
         conexion.closeConexion();
   
         CreateProduct createProduct = new CreateProduct(block,type,id);
         createProduct.setVisible(true);
         this.setVisible(false);
        }
               
    }//GEN-LAST:event_jButtonCreateModifyActionPerformed

    private void jTextDescriptionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextDescriptionKeyTyped
     
        if(jTextDescription.getText().length()>=100) evt.consume();
        
    }//GEN-LAST:event_jTextDescriptionKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Run.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Run.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Run.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Run.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Run().setVisible(true);
            }
        });
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonCreateModify;
    private javax.swing.JComboBox jComboType;
    private javax.swing.JComboBox jComboWidth;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextDate;
    private javax.swing.JTextArea jTextDescription;
    // End of variables declaration//GEN-END:variables
}
